#################
# Estimate Models for Simulations

library(foreign)

# Source Estitmation Script 
source("99_est_stan_simdat.R")

# SAMPLING PARAMTERS
options(echo=TRUE) # if you want see commands in output file
CHAINS <- 4
ITER <- 1000


# Loop over csv-simulation files
for(file in grep("simulation_dat",dir("./"),value = T)){
  
    d <- read.csv(paste(DIR,file,sep=""))
    res <- est_stan_sim(dat=d,iteration=ITER, chains=CHAINS)
    saveRDS(res,paste("res_",file,".Rds",sep=""))
  
}

# Combine to Data.frame


cd <- data.frame()

for(file in dir(DIR)){
  
  fit <- readRDS(paste("out/res_",file,".Rds",sep=""))
  d <- summary(fit,probs = c(0.01,0.025, 0.25, 0.50, 0.75, 0.975,0.99))$summary
  d <- as.data.frame(d)
  d$par <- rownames(d)
  rownames(d) <- NULL
  name_split <- strsplit(file,"_")[[1]]
  d$type <- ifelse(length(name_split)==5,paste(name_split[3:4],collapse=" "),name_split[3])
  d$parties <- strtrim(name_split[length(name_split)],1)
  cd <- rbind(cd,d)
  
}

saveRDS(cd,"res_simulation_combined.Rds")
